<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <XForm :fieldList="otherField" :formOption="optionsData" :formData="form">
      </XForm>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
    <template #operation="{ row }">
      <div class="flex items-center">
        <el-button
          v-if="row.audit_status === 0 || row.audit_status === 2"
          link
          type="primary"
          @click="handleSubmit(row.id)"
          v-hasPermi="[financeManageAuthList.tail_bills.submit]"
        >
          提交
        </el-button>
        <el-button
          v-if="row.audit_status === 3"
          link
          type="primary"
          @click="handleConfirm(row.id)"
          v-hasPermi="[financeManageAuthList.tail_bills.confirm]"
        >
          确认
        </el-button>
        <el-button
          v-if="row.audit_status === 4"
          link
          type="primary"
          @click="handleApproval(row)"
          v-hasPermi="[financeManageAuthList.tail_bills.audit]"
        >
          审核
        </el-button>
        <el-button
          link
          type="primary"
          @click="handleLog(row)"
          v-hasPermi="[financeManageAuthList.tail_bills.log]"
        >
          日志
        </el-button>
      </div>
    </template>
  </VTable>
  <import-dialog ref="importDialogRef" @refresh="refresh" />
  <BatchConfirm
    type="other"
    v-model="confirmVisible"
    :rows="selectRows"
    @close="selectRows = ''"
    @refresh="refresh"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <ConfirmInput
    title="审核"
    class="w-[500px]"
    confirmButtonText="确认"
    v-model="approvalVisible"
    :loading="loading"
    :field-options="approvalOptions"
    :rules="approvalRules"
    @submit="handleApprovalReq"
  />
  <Log
    dialog
    v-model="logVisible"
    :autoLoad="false"
    tag="finance.tail-other-fee"
    :business_id="logId"
    @close="logId = ''"
  />
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { otherField } from "../../config.js";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import { otherFeeList, otherFeeSubmit, otherAudit } from "../../api/index";
import XForm from "@/components/XForm/index.vue";
import importDialog from "@/components/importDialog/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { getTableSelectRow } from "@/hooks/tool.js";
import Log from "@/components/Log/index.vue";
import { config_name } from "@/config/export.js";
import BatchConfirm from "../BatchConfirm/index";
import ConfirmInput from "@/components/ConfirmInput/index.vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", title: "账户名称", width: 200, field: "account_name" },
    {
      fixed: "left",
      title: "出账仓库",
      width: 200,
      field: "out_bill_warehouse_name",
    },
    { title: "交易号", width: 200, field: "trade_number" },
    { title: "费用名称", width: 200, field: "cost_label" },
    {
      title: "流水类型",
      width: 200,
      field: "fee_type",
    },
    { title: "金额", width: 140, field: "origin_cost" },
    { title: "币种", width: 140, field: "currency" },
    { title: "备注", width: 140, field: "remark", showOverflow: true },
    { title: "状态", width: 90, field: "audit_status_label" },
    {
      title: "添加人\n添加时间",
      width: 170,
      slots: {
        default: ({ row }) => {
          return (
            <div>
                <p>{row?.create_userx||'-'}</p>
                <p>{row?.create_time||'-'}</p>
            </div>
          );
        },
      },
    },
    {
      title: "审核人\n审核时间",
      width: 170,
      slots: {
        default: ({ row }) => {
          return (
            <div>
                <p>{row?.audit_user||'-'}</p>
                <p>{row?.audit_time||'-'}</p>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return otherFeeList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
//导入费用
const importDialogRef = ref();
const handleImport = () => {
  importDialogRef.value?.open({
    type: "finance.tailOtherFee",
    urlType: "/finance/tail-other-fee/import",
  });
};

//批量确认及备注
const confirmVisible = ref(false);
const selectRows = ref([]);
const handleBatchConfirm = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  confirmVisible.value = true;
  selectRows.value = records;
};
const handleConfirm = (e) => {
  confirmVisible.value = true;
  selectRows.value = [{ id: e }];
};

//提交
const handleSubmit = (id) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认提交该条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await otherFeeSubmit({ id });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("提交成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//审核
const approvalVisible = ref(false);
const loading = ref(false);
const approvalOptions = [
  {
    label: "审核状态",
    field: "audit",
    type: "radio",
    style: { width: "100%" },
    options: {
      data: [
        { label: "通过", value: "pass" },
        { label: "驳回", value: "rejected" },
      ],
    },
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
    },
  },
  {
    label: "驳回原因",
    field: "remark",
    type: "textarea",
    style: { marginTop: "10px" },
    autosize: { minRows: 4, maxRows: 8 },
    show: ({ model }) => model.audit === "rejected",
  },
];
const approvalRules = {
  audit: [{ required: true, message: "请选择审核状态", trigger: "blur" }],
};
const approvalId = ref({});
const handleApproval = (val) => {
  approvalId.value = val;
  approvalVisible.value = true;
};
const handleApprovalReq = async (formValues) => {
  const _id = approvalId.value?.id;
  try {
    loading.value = true;
    const { code, message } = await otherAudit({
      id: _id,
      ...formValues,
    });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("操作成功");
    approvalId.value = {};
    approvalVisible.value = false;
    refresh();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

//日志
const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

//导出
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["tail_other_fee"],
    condition,
  });
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const actions = [
  {
    label: "导入费用",
    type: "primary",
    fn: handleImport,
    permission: [financeManageAuthList.tail_bills.costimport],
  },
  {
    label: "批量确认及备注",
    type: "primary",
    fn: handleBatchConfirm,
    permission: [financeManageAuthList.tail_bills.moreconfirm],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [financeManageAuthList.tail_bills.export],
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
</style>
